import { _decorator, Button, Component, director, EventHandler, Animation, game, math, Sprite, UITransform, view, Widget, AnimationClip, sys, } from 'cc';
import { createUILabel, createUINode, getFrameAsset, loadAnimationClip } from '../utils';
import { EVENT_ENUM, GAME_MODE_ENUM, PLAYER_ENUM } from '../../Enums';
import EventManager from '../Runtime/EventManager';
import DataManager from '../Runtime/DataManager';
import { JoyStickManager } from './JoyStickManager';
import { JoyAttackManager } from './JoyAttackManager';
import { TileMapManager } from '../Tile/TileMapManager';
import { CollisionDetection } from '../Runtime/CollisionDetection';
import { userStore } from '../service/user';
import { info } from '../api/info';
import { AdManager } from './AdManager';
import { roomUpdate } from '../api/game';
const { ccclass } = _decorator;
const wx = window['wx']
@ccclass('GameElement')
export class GameElement extends Component {
    operationNode
    controllerManager
    fractionNumber
    designSize
    play_music: boolean
    commonElement
    adManager
    init({ controllerManager, play_music, commonElement }) {
        this.play_music = play_music
        this.controllerManager = controllerManager
        this.commonElement = commonElement
        this.createOperatingButton()
        const adManager = this.node.addComponent(AdManager)
        adManager.init()
        this.adManager = adManager
    }
    onLoad() {
        EventManager.Instance.on(EVENT_ENUM.RESTRAT_GAME, this.changeCloseButton, this);
        
    }
    onDestroy() {
        DataManager.Instance.drawerNumber = 0
        EventManager.Instance.off(EVENT_ENUM.RESTRAT_GAME, this.changeCloseButton);
    }
    // 初始化按钮
    async createOperatingButton() {
        const operationNode = createUINode('operationNode')
        operationNode.setParent(this.node.parent.getChildByName('gameNode'))
        operationNode.setSiblingIndex(99)
        DataManager.Instance.operationNode = operationNode
        this.operationNode = operationNode
        let designSize = view.getVisibleSize()
        const transform = operationNode.getComponent(UITransform)
        transform.setContentSize(designSize.width, designSize.height)
        this.designSize = designSize
        // 暂停游戏
        this.changeGameStatus(operationNode)
        // 音频按钮
        this.audioMute(operationNode)
        // 虚拟摇杆
        // if (sys.isMobile) {
           this.initJoyStick(operationNode)
        // }
        // 左下角小人状态
        this.roleEatStatus(operationNode)
        // 分数
        this.setFraction(operationNode)
        if (DataManager.Instance.gameMode == GAME_MODE_ENUM.ONLINE) {
            // 网络延时
            this.setDelayed()
        }
        if (DataManager.Instance.gameMode != GAME_MODE_ENUM.SINGLE) {
            this.roleEatStatusRight(operationNode)
        }
    }
    setDelayed() {
        const node = createUINode("delayed")
        node.setParent(this.operationNode)
        const widget = node.addComponent(Widget)
        widget.isAlignLeft = true
        widget.left = 50
        widget.isAlignTop = true
        widget.top = 15
        const delayedNumber = createUINode("delayedNumber")
        delayedNumber.setParent(node)
        DataManager.Instance.delayedNumber = delayedNumber
        createUILabel({ parentNode: delayedNumber, text: DataManager.Instance.ping_time + 'ms', color: '#fbfbfd', fontSize: 40 })
        const delayedWidget = delayedNumber.addComponent(Widget)
        delayedWidget.isAlignLeft = true
        delayedWidget.left = 260
    }
    // 分数
    setFraction(operationNode) {
        const node = createUINode('fraction')
        node.setParent(operationNode)
        const widget = node.addComponent(Widget)
        widget.isAlignLeft = true
        widget.left = 50
        widget.isAlignTop = true
        widget.top = 15
        const fractionLabel = createUINode("fractionLabel")
        fractionLabel.setParent(node)
        createUILabel({ parentNode: fractionLabel, text: '分数:', color: '#fbfbfd', fontSize: 40 })
        const fractionNumber = createUINode("fractionNumber")
        fractionNumber.setParent(node)
        this.fractionNumber = fractionNumber
        createUILabel({ parentNode: fractionNumber, text: DataManager.Instance.fraction + '', color: '#fbfbfd', fontSize: 40 })
        const fractionWidget = fractionNumber.addComponent(Widget)
        fractionWidget.isAlignLeft = true
        fractionWidget.left = 110
        DataManager.Instance.fractionNumber = fractionNumber

    }
    async initJoyStick(operationNode) {
        const node = createUINode("joyStick")
        node.setParent(operationNode)
        const transform = node.getComponent(UITransform)
        transform.setContentSize(this.designSize.width / 2 - 150, this.designSize.height / 2)
        transform.setAnchorPoint(0, 0)
        const widget = node.addComponent(Widget)
        widget.isAlignBottom = true
        widget.bottom = 0
        widget.isAlignLeft = true
        widget.left = 0
        const body = createUINode("Body")
        body.setParent(node)
        body.setPosition(400, 200)
        const bodyTransform = body.getComponent(UITransform)
        bodyTransform.setContentSize(300, 300)
        const bodySprite = body.addComponent(Sprite)
        bodySprite.sizeMode = Sprite.SizeMode.CUSTOM
        bodySprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, 'circle.png').spriteFrame
        bodySprite.color = new math.Color("#fbfbfd70")
        const stick = createUINode("Stick")
        stick.setParent(body)
        const stickTransform = stick.getComponent(UITransform)
        stickTransform.setContentSize(90, 90)
        const stickSprite = stick.addComponent(Sprite)
        stickSprite.sizeMode = Sprite.SizeMode.CUSTOM
        stickSprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, 'circle2.png').spriteFrame
        stickSprite.color = new math.Color("#1d1b1f")
        const joyStickManager = node.addComponent(JoyStickManager)
        joyStickManager.init()
        this.initAttackNode(operationNode)
    }
    initAttackNode(operationNode) {
        const node = createUINode("attack_node")
        node.setParent(operationNode)
        const transform = node.getComponent(UITransform)
        transform.setContentSize(this.designSize.width / 2 - 150, this.designSize.height / 2)
        transform.setAnchorPoint(0, 0)
        const widget = node.addComponent(Widget)
        widget.isAlignBottom = true
        widget.bottom = 0
        widget.isAlignRight = true
        widget.right = 0
        const body = createUINode("Body")
        body.setParent(node)
        body.setPosition(500, 200)
        const bodyTransform = body.getComponent(UITransform)
        bodyTransform.setContentSize(260, 260)
        const bodySprite = body.addComponent(Sprite)
        bodySprite.sizeMode = Sprite.SizeMode.CUSTOM
        bodySprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, 'circle3.png').spriteFrame
        bodySprite.color = new math.Color("#fbfbfd80")
        const joyAttackManager = node.addComponent(JoyAttackManager)
        joyAttackManager.init()
    }


    //暂停/开始游戏
    async changeGameStatus(operationNode) {
        const node = createUINode('pauseGame')
        node.setParent(operationNode)
        const transform = node.getComponent(UITransform)
        transform.setContentSize(50, 50)
        const widget = node.addComponent(Widget)
        widget.isAlignTop = true
        widget.top = 50
        widget.isAlignRight = true
        if (sys.isMobile && typeof (wx) !== "undefined") {
            widget.right = 300
        } else {
            widget.right = 100
        }
        const sprite = node.addComponent(Sprite)
        sprite.sizeMode = Sprite.SizeMode.CUSTOM
        sprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, '843.png').spriteFrame
        const button = node.addComponent(Button)
        button.duration = .1
        button.zoomScale = 0.95
        button.transition = Button.Transition.SCALE
        const eventHandler = new EventHandler();
        eventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
        eventHandler.component = 'GameElement';// 这个是脚本类名
        eventHandler.handler = DataManager.Instance.gameMode == GAME_MODE_ENUM.ONLINE ? 'onlinePause' : 'pauseGame';
        eventHandler.customEventData = "pauseGame"
        button.clickEvents.push(eventHandler)

        const closeNode = createUINode("closeNode")
        closeNode.setParent(node)
        closeNode.active = false
        const closeTransform = closeNode.getComponent(UITransform)
        closeTransform.setContentSize(35, 35)
        const closeSprite = closeNode.addComponent(Sprite)
        closeSprite.sizeMode = Sprite.SizeMode.CUSTOM
        closeSprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, '493.png').spriteFrame// spriteFrame.find(item => item.name == '493')
    }
    // 设置禁用状态
    changeCloseButton(name) {
        let node = this.operationNode.getChildByName(name)
        let closeNode = node.getChildByName("closeNode")
        closeNode.active = !closeNode.active
    }
    async onlinePause() {
        if (DataManager.Instance.drawerNumber != 0) {
            return
        }
        if (DataManager.Instance.player.length == 0) return
        this.changeCloseButton("pauseGame")
        let { maskBox } = await this.controllerManager.showDrawerContent({ name: 'pauseGameMask', tips: "游戏暂停", node: DataManager.Instance.operationNode, showCancle: false })
        const revertNode = createUINode("revertNode")
        revertNode.setParent(maskBox)
        const button = revertNode.addComponent(Button)
        const clickEventHandler = new EventHandler();
        clickEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
        clickEventHandler.component = 'GameElement';// 这个是脚本类名
        clickEventHandler.handler = 'onlineHome';
        button.duration = .1
        button.zoomScale = 0.95
        button.transition = Button.Transition.SCALE
        button.clickEvents.push(clickEventHandler)
        createUILabel({ parentNode: revertNode, text: "返回首页" })
        const revertWidget = revertNode.addComponent(Widget)
        revertWidget.isAlignBottom = true
        revertWidget.bottom = 30
        revertWidget.isAlignLeft = true
        revertWidget.left = 60

        const alignNode = createUINode("alignNode")
        alignNode.setParent(maskBox)
        const alignButton = alignNode.addComponent(Button)
        const alignEventHandler = new EventHandler();
        alignEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
        alignEventHandler.component = 'GameElement';// 这个是脚本类名
        alignEventHandler.handler = 'continuePlaying';
        alignButton.duration = .1
        alignButton.zoomScale = 0.95
        alignButton.transition = Button.Transition.SCALE
        alignButton.clickEvents.push(alignEventHandler)
        createUILabel({ parentNode: alignNode, text: "继续游戏" })
        const alignWidget = alignNode.addComponent(Widget)
        alignWidget.isAlignBottom = true
        alignWidget.bottom = 30
        alignWidget.isAlignRight = true
        alignWidget.right = 60
    }
    // 在线模式离开房间
    onlineHome() {
        this.controllerManager.showMiniLoading({ tips: "确定要返回首页吗?" }).then(res => {
            DataManager.Instance.room = null
            this.goHome()
        })
        // this.controllerManager.showMiniLoading({
        //     tips: "确定要返回首页吗?",
        //     cancel_text: "再想想",
        //     confirm_text: "确定",
        //     confirm_target: this.node,
        //     confirm_component: "GameElement",
        //     confirm_handler: "goHome"
        // })
    }
    // 修改房间状态
    updateRoom() {
        if (DataManager.Instance.gameMode == GAME_MODE_ENUM.ONLINE) {
            roomUpdate({ id: DataManager.Instance.room.id, status: 0 }).then(res => {
                console.log(res)
            })
        }
    }
    // 暂停/开始游戏事件
    async pauseGame() {
        if (DataManager.Instance.drawerNumber != 0) {
            return
        }
        if (!game.isPaused()) {
            if (DataManager.Instance.player.length == 0) return
            this.changeCloseButton("pauseGame")
            let { maskBox } = await this.controllerManager.showDrawerContent({ name: 'pauseGameMask', tips: "游戏暂停", node: DataManager.Instance.operationNode, showCancle: false })
            const revertNode = createUINode("revertNode")
            revertNode.setParent(maskBox)
            const button = revertNode.addComponent(Button)
            const clickEventHandler = new EventHandler();
            clickEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
            clickEventHandler.component = 'GameElement';// 这个是脚本类名
            clickEventHandler.handler = 'goHome';
            button.duration = .1
            button.zoomScale = 0.95
            button.transition = Button.Transition.SCALE
            button.clickEvents.push(clickEventHandler)
            createUILabel({ parentNode: revertNode, text: "返回首页" })
            const revertWidget = revertNode.addComponent(Widget)
            revertWidget.isAlignBottom = true
            revertWidget.bottom = 30
            revertWidget.isAlignLeft = true
            revertWidget.left = 60

            const alignNode = createUINode("alignNode")
            alignNode.setParent(maskBox)
            const alignButton = alignNode.addComponent(Button)
            const alignEventHandler = new EventHandler();
            alignEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
            alignEventHandler.component = 'GameElement';// 这个是脚本类名
            alignEventHandler.handler = 'continuePlaying';
            alignButton.duration = .1
            alignButton.zoomScale = 0.95
            alignButton.transition = Button.Transition.SCALE
            alignButton.clickEvents.push(alignEventHandler)
            createUILabel({ parentNode: alignNode, text: "继续游戏" })
            const alignWidget = alignNode.addComponent(Widget)
            alignWidget.isAlignBottom = true
            alignWidget.bottom = 30
            alignWidget.isAlignRight = true
            alignWidget.right = 60
            setTimeout(() => {
                game.pause()
            }, 100)

        } else {
            game.resume()
            this.changeCloseButton("pauseGame")
        }
    }
    continuePlaying() {
        // game.resume()
        this.changeCloseButton("pauseGame")
        this.controllerManager.close('pauseGameMask')
    }
    // 静音/播放
    async audioMute(operationNode) {
        const node = createUINode('audioMute')
        node.setParent(operationNode)
        const transform = node.getComponent(UITransform)
        transform.setContentSize(50, 50)
        const widget = node.addComponent(Widget)
        widget.isAlignTop = true
        widget.top = 50
        widget.isAlignRight = true
        if (sys.isMobile && typeof (wx) !== "undefined") {
            widget.right = 400
        } else {
            widget.right = 200
        }
        const sprite = node.addComponent(Sprite)
        sprite.sizeMode = Sprite.SizeMode.CUSTOM
        sprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, '821.png').spriteFrame //spriteFrame.find(item => item.name == "821")
        const button = node.addComponent(Button)
        button.duration = .1
        button.zoomScale = 0.95
        button.transition = Button.Transition.SCALE
        const eventHandler = new EventHandler();
        eventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
        eventHandler.component = 'GameElement';// 这个是脚本类名
        eventHandler.handler = 'changeAudio';
        button.clickEvents.push(eventHandler)

        const closeNode = createUINode("closeNode")
        closeNode.setParent(node)
        closeNode.active = false
        const closeTransform = closeNode.getComponent(UITransform)
        closeTransform.setContentSize(35, 35)
        const closeSprite = closeNode.addComponent(Sprite)
        closeSprite.sizeMode = Sprite.SizeMode.CUSTOM
        closeSprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, '493.png').spriteFrame// spriteFrame.find(item => item.name == '493')
        closeNode.active = DataManager.Instance.mute
    }
    // 静音/播放事件
    changeAudio() {
        // if (DataManager.Instance.drawerNumber != 0) {
        //     return
        // }
        if (DataManager.Instance.mute) {
            if (this.play_music) {
                DataManager.Instance.audioMgr.resume()
            } else {
                DataManager.Instance.audioMgr.play(DataManager.Instance.audio.find(item => item.name == '1256_game_music'),)
                this.play_music = true
            }
        } else {
            DataManager.Instance.audioMgr.pause()
        }
        DataManager.Instance.mute = !DataManager.Instance.mute
        sys.localStorage.setItem('mute', JSON.stringify(DataManager.Instance.mute))
        this.changeCloseButton("audioMute")
    }
    // 左下角小人状态
    async roleEatStatus(operationNode) {
        const node = createUINode(PLAYER_ENUM.BLUE)
        node.setParent(operationNode)
        const widget = node.addComponent(Widget)
        widget.isAlignBottom = true
        widget.bottom = 20
        widget.isAlignLeft = true
        widget.left = 36
        const roleNode = createUINode('roleNode')
        roleNode.setParent(node)
        const roleTransform = roleNode.getComponent(UITransform)
        roleTransform.setContentSize(29 * 2.5, 28 * 2.5)
        const roleSprite = roleNode.addComponent(Sprite)
        // let roleFrame = DataManager.Instance.gameAssets
        roleSprite.sizeMode = Sprite.SizeMode.CUSTOM
        roleSprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, '502.png').spriteFrame// roleFrame.find(item => item.name == '502')

        const statusNode = createUINode('statusNode')
        statusNode.setParent(node)
        const statusWidget = statusNode.addComponent(Widget)
        statusWidget.isAlignTop = true
        statusWidget.top = -60
        const statusTransform = statusNode.getComponent(UITransform)
        statusTransform.setContentSize(26 * 2.5, 28 * 2.5)
        const statusSprite = statusNode.addComponent(Sprite)
        statusSprite.sizeMode = Sprite.SizeMode.CUSTOM
        statusSprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, 'empty.png').spriteFrame// roleFrame.find(item => item.name == 'empty')
    }
    // 右下角小人状态
    async roleEatStatusRight(operationNode) {
        const node = createUINode(PLAYER_ENUM.GREEN)
        node.setParent(operationNode)
        const widget = node.addComponent(Widget)
        widget.isAlignBottom = true
        widget.bottom = 20
        widget.isAlignRight = true
        widget.right = 36
        const roleNode = createUINode('roleNode')
        roleNode.setParent(node)
        const roleTransform = roleNode.getComponent(UITransform)
        roleTransform.setContentSize(29 * 2.5, 28 * 2.5)
        const roleSprite = roleNode.addComponent(Sprite)
        roleSprite.sizeMode = Sprite.SizeMode.CUSTOM
        roleSprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, '504.png').spriteFrame// roleFrame.find(item => item.name == '502')

        const statusNode = createUINode('statusNode')
        statusNode.setParent(node)
        const statusWidget = statusNode.addComponent(Widget)
        statusWidget.isAlignTop = true
        statusWidget.top = -60
        const statusTransform = statusNode.getComponent(UITransform)
        statusTransform.setContentSize(26 * 2.5, 28 * 2.5)
        const statusSprite = statusNode.addComponent(Sprite)
        statusSprite.sizeMode = Sprite.SizeMode.CUSTOM
        statusSprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, 'empty.png').spriteFrame// roleFrame.find(item => item.name == 'empty')
    }
    // 游戏失败
    async createFail() {
        // 修改游戏记录，游戏失败
        this.commonElement.updateCreateRecord(DataManager.Instance.levelInfo, 2)
        this.updateRoom()
        let { content, maskBox } = await this.controllerManager.showDrawerContent({ name: 'clearance', tips: "游戏失败", showCancle: false, node: DataManager.Instance.operationNode })
        let bluePerson = loadAnimationClip(DataManager.Instance.homeAssets, 'blueLead', AnimationClip.WrapMode.Loop)
        const node = createUINode()
        node.setParent(content)
        node.setScale(2, 2)
        const sprite = node.addComponent(Sprite)
        const animation = sprite.addComponent(Animation)
        animation.defaultClip = bluePerson.animation
        animation.play()
        const widget = node.addComponent(Widget)
        widget.isAlignTop = true
        widget.top = 80
        if (DataManager.Instance.gameMode != GAME_MODE_ENUM.SINGLE) {
            widget.isAlignLeft = true
            widget.left = 280
            let greenPerson = loadAnimationClip(DataManager.Instance.homeAssets, 'greenLead', AnimationClip.WrapMode.Loop)
            const green_node = createUINode('greenPerson')
            green_node.setParent(content)
            green_node.setScale(2, 2)
            const green_sprite = green_node.addComponent(Sprite)
            const green_animation = green_sprite.addComponent(Animation)
            green_animation.defaultClip = greenPerson.animation
            green_animation.play()

            const green_widget = green_node.addComponent(Widget)
            green_widget.isAlignTop = true
            green_widget.top = 80
            green_widget.isAlignRight = true
            green_widget.right = 260
        }
        const failNode = createUINode()
        failNode.setParent(content)
        createUILabel({ parentNode: failNode, text: `分数:${DataManager.Instance.fraction}` })
        if (DataManager.Instance.gameMode == GAME_MODE_ENUM.ONLINE) {
            const revertNode = createUINode("revertNode")
            revertNode.setParent(maskBox)
            const button = revertNode.addComponent(Button)
            const clickEventHandler = new EventHandler();
            clickEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
            clickEventHandler.component = 'GameElement';// 这个是脚本类名
            clickEventHandler.handler = 'goHome';
            button.duration = .1
            button.zoomScale = 0.95
            button.transition = Button.Transition.SCALE
            button.clickEvents.push(clickEventHandler)
            createUILabel({ parentNode: revertNode, text: "返回首页" })
            const revertWidget = revertNode.addComponent(Widget)
            revertWidget.isAlignBottom = true
            revertWidget.bottom = 30
            // revertWidget.isAlignVerticalCenter = true
        } else {
            const revertNode = createUINode("revertNode")
            revertNode.setParent(maskBox)
            const button = revertNode.addComponent(Button)
            const clickEventHandler = new EventHandler();
            clickEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
            clickEventHandler.component = 'GameElement';// 这个是脚本类名
            clickEventHandler.handler = 'goHome';
            button.duration = .1
            button.zoomScale = 0.95
            button.transition = Button.Transition.SCALE
            button.clickEvents.push(clickEventHandler)
            createUILabel({ parentNode: revertNode, text: "返回房间" })
            const revertWidget = revertNode.addComponent(Widget)
            revertWidget.isAlignBottom = true
            revertWidget.bottom = 30
            revertWidget.isAlignLeft = true
            revertWidget.left = 60

            const alignNode = createUINode("alignNode")
            alignNode.setParent(maskBox)
            const alignButton = alignNode.addComponent(Button)
            const alignEventHandler = new EventHandler();
            alignEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
            alignEventHandler.component = 'GameElement';// 这个是脚本类名
            alignEventHandler.handler = 'restartGame';
            alignButton.duration = .1
            alignButton.zoomScale = 0.95
            alignButton.transition = Button.Transition.SCALE
            alignButton.clickEvents.push(alignEventHandler)
            createUILabel({ parentNode: alignNode, text: "重新开始" })
            const alignWidget = alignNode.addComponent(Widget)
            alignWidget.isAlignBottom = true
            alignWidget.bottom = 30
            alignWidget.isAlignRight = true
            alignWidget.right = 60
        }

    }
    // 游戏过关
    async createAchieve() {
        // 修改游戏记录，游戏过关，并且解锁下一条游戏id
        this.commonElement.updateCreateRecord(DataManager.Instance.levelInfo, 1)
        this.updateRoom()
        let { content, maskBox } = await this.controllerManager.showDrawerContent({ name: 'clearance', tips: "恭喜过关", showCancle: false, node: DataManager.Instance.operationNode })
        DataManager.Instance.audioMgr.playOneShot(DataManager.Instance.audio.find(item => item.name == '1239'))
        let bluePerson = loadAnimationClip(DataManager.Instance.blueLeadAssets, 'win', AnimationClip.WrapMode.Loop)
        const node = createUINode('bluePerson')
        node.setParent(content)
        node.setScale(2, 2)
        const sprite = node.addComponent(Sprite)
        const animation = sprite.addComponent(Animation)
        animation.defaultClip = bluePerson.animation
        animation.play()

        const widget = node.addComponent(Widget)
        widget.isAlignTop = true
        widget.top = 80
        const achieveNode = createUINode()
        achieveNode.setParent(content)
        createUILabel({ parentNode: achieveNode, text: `分数:${DataManager.Instance.fraction}` })
        if (DataManager.Instance.gameMode != GAME_MODE_ENUM.SINGLE) {
            widget.isAlignLeft = true
            widget.left = 280
            let greenPerson = loadAnimationClip(DataManager.Instance.greenLeadAssets, 'win', AnimationClip.WrapMode.Loop)
            const green_node = createUINode('greenPerson')
            green_node.setParent(content)
            green_node.setScale(2, 2)
            const green_sprite = green_node.addComponent(Sprite)
            const green_animation = green_sprite.addComponent(Animation)
            green_animation.defaultClip = greenPerson.animation
            green_animation.play()

            const green_widget = green_node.addComponent(Widget)
            green_widget.isAlignTop = true
            green_widget.top = 80
            green_widget.isAlignRight = true
            green_widget.right = 260
        }
        if (DataManager.Instance.gameMode == GAME_MODE_ENUM.ONLINE) {
            const revertNode = createUINode("revertNode")
            revertNode.setParent(maskBox)
            const button = revertNode.addComponent(Button)
            const clickEventHandler = new EventHandler();
            clickEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
            clickEventHandler.component = 'GameElement';// 这个是脚本类名
            clickEventHandler.handler = 'goHome';
            button.duration = .1
            button.zoomScale = 0.95
            button.transition = Button.Transition.SCALE
            button.clickEvents.push(clickEventHandler)
            createUILabel({ parentNode: revertNode, text: "返回房间" })
            const revertWidget = revertNode.addComponent(Widget)
            revertWidget.isAlignBottom = true
            revertWidget.bottom = 30
            // revertWidget.isAlignVerticalCenter = true
        } else {
            const revertNode = createUINode("revertNode")
            revertNode.setParent(maskBox)
            const button = revertNode.addComponent(Button)
            const clickEventHandler = new EventHandler();
            clickEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
            clickEventHandler.component = 'GameElement';// 这个是脚本类名
            clickEventHandler.handler = 'goHome';
            button.duration = .1
            button.zoomScale = 0.95
            button.transition = Button.Transition.SCALE
            button.clickEvents.push(clickEventHandler)
            createUILabel({ parentNode: revertNode, text: "返回首页" })
            const revertWidget = revertNode.addComponent(Widget)
            revertWidget.isAlignBottom = true
            revertWidget.bottom = 30
            revertWidget.isAlignLeft = true
            revertWidget.left = 60

            const alignNode = createUINode("alignNode")
            alignNode.setParent(maskBox)
            const alignButton = alignNode.addComponent(Button)
            const alignEventHandler = new EventHandler();
            alignEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
            alignEventHandler.component = 'GameElement';// 这个是脚本类名
            alignEventHandler.handler = 'nextLevel';
            alignButton.duration = .1
            alignButton.zoomScale = 0.95
            alignButton.transition = Button.Transition.SCALE
            alignButton.clickEvents.push(alignEventHandler)
            createUILabel({ parentNode: alignNode, text: "下一关" })
            const alignWidget = alignNode.addComponent(Widget)
            alignWidget.isAlignBottom = true
            alignWidget.bottom = 30
            alignWidget.isAlignRight = true
            alignWidget.right = 60
        }

    }
    // 游戏通关
    async createClearance() {
        // 同游戏过关
        this.commonElement.updateCreateRecord(DataManager.Instance.levelInfo, 1)
        this.updateRoom()
        let { content, maskBox } = await this.controllerManager.showDrawerContent({ name: 'clearance', tips: "恭喜你,全部过关!", showCancle: false, node: DataManager.Instance.operationNode })
        DataManager.Instance.audioMgr.playOneShot(DataManager.Instance.audio.find(item => item.name == '1239'))
        let clearance = getFrameAsset(DataManager.Instance.homeAssets, '1221.png').spriteFrame //DataManager.Instance.commonAssets.find(item=>item.name=='1221')
        const node = createUINode()
        node.setParent(content)
        node.setScale(2, 2)
        const sprite = node.addComponent(Sprite)
        sprite.spriteFrame = clearance
        // sprite.trim = false
        const labelNode = createUINode("revertNode")
        labelNode.setParent(content)
        createUILabel({ parentNode: labelNode, text: "你从地牢里\n逃出来啦!", fontSize: 50, lineHeight: 60 })
        const labelWidget = labelNode.addComponent(Widget)
        labelWidget.isAlignLeft = true
        labelWidget.left = 100
        labelWidget.isAlignTop = true
        labelWidget.top = 140

        const revertNode = createUINode("revertNode")
        revertNode.setParent(maskBox)
        const button = revertNode.addComponent(Button)
        const clickEventHandler = new EventHandler();
        clickEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
        clickEventHandler.component = 'GameElement';// 这个是脚本类名
        clickEventHandler.handler = 'goHome';
        button.duration = .1
        button.zoomScale = 0.95
        button.transition = Button.Transition.SCALE
        button.clickEvents.push(clickEventHandler)
        createUILabel({ parentNode: revertNode, text: "返回首页" })
        const revertWidget = revertNode.addComponent(Widget)
        revertWidget.isAlignBottom = true
        revertWidget.bottom = 30
        revertWidget.isAlignHorizontalCenter = true
    }
    // 重新开始
    async restartGame() {
        let ad = await this.adManager.playAd()
        if (!ad) return
        this.commonElement.setCreateRecord(DataManager.Instance.levelInfo, "gameManager")
        this.clearLevel()
        DataManager.Instance.reset()
        EventManager.Instance.emit('restartGame');
        this.controllerManager.close('clearance')
    }
    // 下一关
    async nextLevel() {
        let ad = await this.adManager.playAd()
        if (!ad) return
        this.node.parent.getChildByName('gameNode').setPosition(0, 0)
        let level = await this.getLevelsInfo()
        DataManager.Instance.levelInfo = level
        // DataManager.Instance.levelInfo.levels=level
        DataManager.Instance.reset()
        this.restartGame()
    }
    // 获取关卡详情
    getLevelsInfo() {
        return info(DataManager.Instance.levelInfo.nextLevel).then(res => {
            res.levels = JSON.parse(res.levels)
            return res
        })
    }
    // 清空关卡
    clearLevel() {
        this.node.getComponent(TileMapManager).destroy()
        this.node.getComponent(CollisionDetection).destroy()
        this.node.destroyAllChildren();
    }
    // 回到首页
    goHome() {
        if (game.isPaused()) {
            game.resume()
        }
        if (DataManager.Instance.gameMode != GAME_MODE_ENUM.ONLINE) {
            this.commonElement.updateCreateRecord(DataManager.Instance.levelInfo, 3)
        }
        DataManager.Instance.reset()
        if (userStore().info?.id) {
            director.loadScene("home")
        } else {
            director.loadScene("login")
        }

    }
}


